// pages/qrcode/qrcode.js
const QR = require("../../utils/qrcode.js");
// 创建激励广告
let rewardedVideoAd = null
let temp = false;
Page({
    data: {
        /*
        官网说hidden只是简单的控制显示与隐藏，组件始终会被渲染，
        但是将canvas转化成图片走的居然是fail，hidden为false就是成功的
        所以这里手动控制显示隐藏canvas
        */
        maskHidden: true,
        imagePath: '',
        placeholder: 'baidu.com',
        buttonText: '观看广告生成二维码'
    },
    onLoad: function (options) {
        const that = this;
        // 页面初始化 options为页面跳转所带来的参数
        const size = this.setCanvasSize();//动态设置画布大小
        const initUrl = "https://" + this.data.placeholder;
        this.createQrCode(initUrl, "mycanvas", size.w, size.h);
        if (wx.createRewardedVideoAd) {
            rewardedVideoAd = wx.createRewardedVideoAd({adUnitId: 'adunit-41bd82d2483d7509'})
            rewardedVideoAd.onLoad(() => {
                console.log('onLoad event emit')
            })
            rewardedVideoAd.onError((err) => {
                rewardedVideoAd.load();
                console.log('拉取广告失败', err)

            })
            rewardedVideoAd.onClose((res) => {
                console.log('onClose event emit', res)
                // 用户点击了【关闭广告】按钮
                if (res && res.isEnded) {
                    // 正常播放结束，可以下发游戏奖励
                    temp = true;
                    that.setData({
                        buttonText: '生成二维码',
                    });
                } else {
                    // 播放中途退出，不下发游戏奖励
                    temp = false;
                }
            })
        }
    },
    onReady: function () {

    },
    onShow: function () {

        // 页面显示
    },
    onHide: function () {
        // 页面隐藏
    },

    onUnload: function () {
        // 页面关闭

    },
    //适配不同屏幕大小的canvas
    setCanvasSize: function () {
        const size = {};
        try {
            const res = wx.getSystemInfoSync();
            const scale = 750 / 686;//不同屏幕下canvas的适配比例；设计稿是750宽
            const width = res.windowWidth / scale;
            const height = width;//canvas画布为正方形
            size.w = width;
            size.h = height;
        } catch (e) {
            // Do something when catch error
            console.log("获取设备信息失败" + e);
        }
        return size;
    },
    createQrCode: function (url, canvasId, cavW, cavH) {
        //调用插件中的draw方法，绘制二维码图片
        QR.qrApi.draw(url, canvasId, cavW, cavH);
        const that = this;
        //二维码生成之后调用canvasToTempImage();延迟3s，否则获取图片路径为空
        const st = setTimeout(function () {
            that.canvasToTempImage();
            clearTimeout(st);
        }, 3000);

    },
    //获取临时缓存照片路径，存入data中
    canvasToTempImage: function () {
        const that = this;
        wx.canvasToTempFilePath({
            canvasId: 'mycanvas',
            success: function (res) {
                const tempFilePath = res.tempFilePath;
                console.log(tempFilePath);
                that.setData({
                    imagePath: tempFilePath,
                });
            },
            fail: function (res) {
                console.log(res);
            }
        });
    },
    //点击图片进行预览，长按保存分享图片
    previewImg: function (e) {
        const img = this.data.imagePath;
        wx.previewImage({
            current: img, // 当前显示图片的http链接
            urls: [img] // 需要预览的图片http链接列表
        })
    },
    formSubmit: function (e) {
        if (temp) {
            const that = this;
            let url = e.detail.value.url;
            url = url == '' ? ('http://' + that.data.placeholder) : ('http://' + url);
            that.setData({
                maskHidden: false,
            });
            wx.showToast({
                title: '生成中...',
                icon: 'loading',
                duration: 2000
            });
            const st = setTimeout(function () {
                wx.hideToast()
                const size = that.setCanvasSize();
                //绘制二维码
                that.createQrCode(url, "mycanvas", size.w, size.h);
                that.setData({
                    maskHidden: true
                });
                clearTimeout(st);
                that.setData({
                    buttonText: "观看广告生成二维码"
                })
            }, 2000);
            temp = false;
        } else {
            rewardedVideoAd.show();
        }
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        return {
            title: '二维码生成器',
            path: 'pages/qrcode/qrcode'
        }
    }
})